﻿#region usings
using System;
using System.Collections.Generic;
using System.ServiceModel.DomainServices.Client;
using InsuranceAdjuster.Web.Services;
#endregion

namespace InsuranceAdjuster.OccasionallyConnected.Messages {
    public class SyncMessageBase : Message {
        protected Boolean BroadcastResults = true;
        protected List<MessageResult> Results = new List<MessageResult>();
        protected Action<Action<List<KeyValuePair<IEntity, EntitySyncOperation>>>> GetDeltaAction = null;

        public SyncMessageBase(String groupName
            , String messageName) {
            this.CacheRules = MessageDataSource.ServerOnly;
            GroupName = groupName;
            MessageName = messageName;
        }

        protected override void OnlineOperation() {
            MarkAsyncStarted();
            MarkAsyncStarted();
            GetDeltaAction.Invoke(entities =>
            {
                Results = new List<MessageResult>();

                if (entities != null && entities.Count > 0) {
                    foreach (var Item in entities) {
                        if (Item.Value == EntitySyncOperation.Add)
                            Results.Add(new MessageResult(Verb.Read, Origin.Server, Item.Key.EntityGuid, Item.Key, BroadcastResults));
                        else if (Item.Value == EntitySyncOperation.Delete)
                            Results.Add(new MessageResult(Verb.Delete, Origin.Server, Item.Key.EntityGuid, Item.Key, BroadcastResults));
                        else if (Item.Value == EntitySyncOperation.Update)
                            Results.Add(new MessageResult(Verb.Update, Origin.Server, Item.Key.EntityGuid, Item.Key, BroadcastResults));
                    }
                }

                MarkAsyncFinished();
            });            
        }

        protected override List<MessageResult> CompileServerResults() {
            return Results;
        }

        #region Other Stuff
        public override void Clear() {
            base.Clear();

            Results = null;
        }
        #endregion
    }
}
